import {
	HEADER,
	BASE_URL,
	TOKENNAME
} from '@/config.js'

export const request = (obj = {
	url: '',
	data: {},
	method: 'GET',
	showMsg: false
}) => {
	let {
		url,
		data,
		method,
		showMsg
	} = obj
	// 获取token
	const token = uni.getStorageSync(TOKENNAME);

	// 请求参数
	let header = {},
		hideLoading = obj.hideLoading || false;

	//拼接完整请求地址
	let requestUrl = BASE_URL + url;

	// 对请求地址进行拼接
	let paramStr = `?${ token ? `token=${ token }` : ''}`
	
	if (method) {
		method = method.toUpperCase(); //小写改为大写
		
		for (let key in data) {
			paramStr += `&${key}=${ typeof data[key] === 'object' ? encodeURIComponent(JSON.stringify(data[key])) : data[key] }`
		}
		header = {
			'Content-Type': 'application/json;charset=UTF-8',
			'Access-Control-Allow-Headers': 'token',
			'Access-Control-Max-Age': 86400,
			'Access-Control-Allow-Origin': '*'
		};
	}
	
	//加载圈
	if (!hideLoading) {
		// uni.showLoading({
		// 	title: 'loading...'
		// });
	}
	console.log(url, data, token)
	// 返回promise
	return new Promise((resolve, reject) => {
		// 请求
		uni.request({
			url: requestUrl + paramStr,
			data: data,
			method: method,
			header: header,
			success: (res) => {
				let {
					data,
					code,
					msg
				} = res.data
				if (code === 0 && !(typeof data === 'string' && data.indexOf(
						'<!doctype html>') > -1)) {
					data = data ? ([undefined, null].includes(data.baseData) ? false : data
						.baseData) : res.data
					console.log(data)
					if (showMsg && data.msg) {
						uni.showToast({
							title: data.msg,
							icon: 'none'
						})
					}
					resolve(data)
				} else {
					reject(res.data)
					if (msg) {
						uni.showToast({
							title: msg,
							icon: 'none'
						})
					}
					console.log(res.data)
					// 101登录失效，103登录过期，102账户冻结
					if ([101, 102, 103].includes(code)) {
						this.$store.commit('UPDATE_USER_INFO', {})
					}
				}
			},
			//请求失败
			fail: (e) => {
				console.log(e)
				let {
					errMsg
				} = e
				if (errMsg.indexOf(
					'request:fail abort statusCode:-1 Unable to resolve host') === -1) {
					uni.showToast({
						title: e.errMsg,
						icon: 'none'
					});
				}
				reject(e);
			},
			//请求完成
			complete() {
				//隐藏加载
				if (!hideLoading) {
					uni.hideLoading();
				}
				resolve();
				return;
			}
		})
	})
}
